package com.aco.party.service.system;

import com.aco.party.dao.custom.RoleDao;
import com.aco.party.dao.custom.RolePermissionDao;
import com.aco.party.model.po.Role;
import com.aco.party.model.po.RoleExample;
import com.aco.party.model.po.RolePermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RoleService {

	@Resource
	private RoleDao roleDao;

	@Autowired
	private RolePermissionDao rolePermissionDao;

	public void addRole(Role role) {
		roleDao.insertSelective(role);
	}

	public void updateRole(Role role) {
		roleDao.updateByPrimaryKey(role);
	}

	public void deleteRole(Long roleId) {
		roleDao.deleteByPrimaryKey(roleId);
	}

	public List<Role> findAllRoles() {

		return roleDao.getAll();
	}

	public Role getRole(Long roleId) {
		return roleDao.selectByPrimaryKey(roleId);
	}

	public Role getRoleByName(String name) {
		RoleExample example = new RoleExample();
		example.createCriteria().andNameEqualTo(name);
		example.setDistinct(true);
		example.setLimit(1L);
		List<Role> roles = roleDao.selectByExample(example);
		if(roles != null && roles.size() > 0)
			return roles.get(0);
		return null;
	}
	public void increasePermission(Long roleId, Long permissionId) {
		if(roleId!=null && permissionId!=null){
			RolePermission rolePermission = new RolePermission();
			rolePermission.setRoleId(roleId);
			rolePermission.setPermissionId(permissionId);
			rolePermissionDao.insertSelective(rolePermission);
		}
	}

	public void decreasePermission(Long roleId, Long permissionId) {
		if(roleId!=null && permissionId!=null){
			RolePermission rolePermission = rolePermissionDao.getByRoleIdAndPermissionId(roleId, permissionId);
			if(rolePermission != null){
				rolePermissionDao.deleteByPrimaryKey(rolePermission.getId());
			}
		}
	}

	public Role getRoleByUserId(Long userId){
		List<Role> roles = roleDao.getRolesByUser(userId);
		if(roles != null && roles.size() > 0){
			return roles.get(0);
		}
		return null;
	}

}
